package com.webcams.ui.downloadmaps;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.webcams.core.download.DownloadMapsManager;
import com.webcams.core.download.IDownloadMapListChangedListener;
import com.webcams.core.resorts.Resort;
import com.webcams.ui.R;

public class DownloadMapsDistPartUI extends ListActivity implements IDownloadMapListChangedListener {

	private ArrayList<Resort> currentList;

	@Override
	public void onCreate(Bundle state) {

		super.onCreate(state);
		setContentView(R.layout.download_maps_dist);
		ListView lv = getListView();

		currentList = new ArrayList<Resort>();

		Button submit = new Button(this);
		submit.setText(getResources().getString(R.string.downloadmaps_distmaps_download));
		submit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(getListView().getCheckedItemPosition() != ListView.INVALID_POSITION) {
					process();
				}
			}
		});
		lv.addHeaderView(submit, null, false);

		listChanged();

		lv.setTextFilterEnabled(true);

		lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		DownloadMapsManager.getInstance(this).addListChangedListener(this);

	}
	
	public void setListFocus(int resortId) {
		/*for(int item : getListView()) {
		
		}*/
	}

	private void process() {

		final DownloadMapsManager mapManager = DownloadMapsManager.getInstance(this);

		final ProgressDialog progressDialog = new ProgressDialog(DownloadMapsDistPartUI.this);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(getResources().getString(R.string.downloadmaps_localmaps_downloadprogress));
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setProgress(0);
		progressDialog.show();

		mapManager.addOrUpdateResort(
				currentList.get(
						getListView().getCheckedItemPosition()-1
				), progressDialog);

	}

	@Override
	public void listChanged() {
		if(currentList != null){
			currentList.clear();

			DownloadMapsManager mapManager = DownloadMapsManager.getInstance(this);

			for(Resort r : mapManager.getResortsNotDownloaded()) {
				currentList.add(r);
			}

			String[] listNames = new String[currentList.size()];
			int i = 0;
			for(Resort r : currentList){
				listNames[i] = r.getName()+" ("+(r.getMapSize()/1024)+" Ko)";
				i++;
			}
			
			setListAdapter(new ArrayAdapter<String>(this, 
					android.R.layout.simple_list_item_single_choice,
					listNames));
		}
	}
}
